<template>
  <div class="search">
    <van-search
      v-model="inputVal"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="$router.back()"
    />
    <my-history v-if="list.length==0" @search="search"></my-history>
    <ul class="content" v-else>
      <li v-for="(item,index) in list" :key="index" @click="$router.push(`/detail/${item.goods_id}`)">
        <img :src="item.goods_big_logo" alt="">
        <section>
          <h6>{{item.goods_name}}</h6>
          <p>￥{{item.goods_price}}</p>
        </section>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import api from "../api/index";
import myHistory from '../components/myHistory.vue';
import { useStore } from 'vuex';
export default {
  components: { myHistory },
  setup() {
    const { commit } = useStore();
    const data = reactive({
      inputVal: "",
      list:[], // 商品列表
    });
    const onSearch = () => {
      api.get(`/goods/search?query=${data.inputVal}`).then((res) => {
        data.list = res.message.goods;
        if(data.inputVal){
            commit('addHistory',data.inputVal)
        }
      });
    };
    const search = (val) => {
       data.inputVal = val;
       onSearch();
    }
    return {
      ...toRefs(data),
      onSearch,
      search
    };
  },
};
</script>
<style lang="scss" scoped>
.search {
  height: 100%;
  .content{
    height: calc(100% - 46px);
    overflow: auto;
    li{
      display: flex;
      padding: 0 10px;
      box-sizing: border-box;
      margin-bottom: 10px;
      img{
        width: 80px;
        margin-right: 10px;
      }
      section{
        flex: 1;
        display: inline-flex;
        flex-wrap: wrap;
        align-content: space-between;
        p{
          color: red;
        }
      }
    }
  }
}
</style>